<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工作时间">
        <el-date-picker
        :clearable="false"
          v-model="queryParams.queryTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" v-hasPermi="['manage:daywork:others']">
        <el-select style="width:120px" v-model="queryParams.userId" placeholder="全部">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
         
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:daywork:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:daywork:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:daywork:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:daywork:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dayworkList" @selection-change="handleSelectionChange">
      <el-table-column :selectable="row=>{return row.userId==nowUserId}" type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="userName">
       
      </el-table-column>
      <el-table-column label="工作时间" align="center" prop="workTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.workTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="工作内容" align="center" prop="content">
        <template #default="scope">
          <div v-html="scope.row.content"></div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button  :disabled="scope.row.userId!=nowUserId" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:daywork:edit']">修改</el-button>
          <el-button :disabled="scope.row.userId!=nowUserId" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:daywork:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作日志信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dayworkRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工作时间" prop="workTime">
          <el-date-picker 
            v-model="form.workTime"
            type="date"
            :clearable="false"
            value-format="YYYY-MM-DD"
            placeholder="请选择工作时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="工作内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Daywork">
function getWeekStartEnd() {
    const now = new Date();
    const day = now.getDay(); // 获取当前是星期几，0 (周日) 到 6 (周六)
    const diff = now.getDate() - day + (day === 0 ? -6 : 1); // 调整日期以找到周一（如果今天不是周一）
 
    const monday = new Date(now.setDate(diff)); // 本周一的日期
    const sunday = new Date(now.setDate(diff + 6)); // 本周日的日期
 
    return { monday, sunday };
}
 
const { monday, sunday } = getWeekStartEnd();
import {  listUser } from "@/api/system/user";
import { listDaywork, getDaywork, delDaywork, addDaywork, updateDaywork } from "@/api/manage/daywork";
import {checkPermi} from '../../../utils/permission.js'
import useUserStore from '@/store/modules/user'
import dayjs from "dayjs"
const { proxy } = getCurrentInstance();
const user = useUserStore()
const nowUserId=user.id
const dayworkList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userList=ref([])
const data = reactive({
  form: {},
  queryParams: {
    userId:user.id,
    pageNum: 1,
    pageSize: 10,
    startTime: dayjs(monday).format('YYYY-MM-DD')+' 00:00:00',
    endTime: dayjs(sunday).format('YYYY-MM-DD')+' 23:59:59',
    queryTime:[dayjs(monday).format('YYYY-MM-DD'),dayjs(sunday).format('YYYY-MM-DD')],
    content: null,
  },
  rules: {
    workTime: [
      { required: true, message: "工作时间不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户 ID不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "工作内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询工作日志信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.startTime=queryParams.value.queryTime[0]+" 00:00:00"
  queryParams.value.endTime=queryParams.value.queryTime[1]+' 23:59:59'
  if(queryParams.value.userId==0){
    queryParams.value.userId=null
  }
  listDaywork(queryParams.value).then(response => {
    dayworkList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询用户列表 */
function getUserList() {
  
  listUser({userType:"01"}).then(res => {
    
    userList.value = res.rows;
    userList.value.push({
      userId:0,
      userName:"全部"
    })
    
  });
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dayworkId: null,
    workTime: dayjs().format('YYYY-MM-DD'),
    userId: null,
    userName:null,
    delFlag: null,
    content: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("dayworkRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dayworkId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加工作日志信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _dayworkId = row.dayworkId || ids.value
  getDaywork(_dayworkId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改工作日志信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dayworkRef"].validate(valid => {
    if (valid) {
      if (form.value.dayworkId != null) {
        updateDaywork(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDaywork(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dayworkIds = row.dayworkId || ids.value;
  proxy.$modal.confirm('是否确认删除工作日志信息编号为"' + _dayworkIds + '"的数据项？').then(function() {
    return delDaywork(_dayworkIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/daywork/export', {
    ...queryParams.value
  }, `工作日志_${new Date().getTime()}.xlsx`)
}

getList();

if(checkPermi(["manage:daywork:others"])){
  getUserList()
}

</script>
